<!-- 布局组件，包括文章列表和文章详情两个界面 -->
<script setup>
import ArticleDetail from '@/views/article/ArticleDetail.vue'
import CateDetail from '@/views/article/CateDetail.vue'
import ArticleComment from './components/Comment.vue'
import MenuBar from './MenuBar.vue'

import { useRoute } from 'vue-router'
import { onMounted, ref, watch } from 'vue'

import useCateInfo from './composable/useCateInfo'  // 获取分类信息
import useArticleList from './composable/useArticleList'  // 获取分类下的文章列表（简略信息）
import useArticleInfo from './composable/useArticleInfo'  // 获取文章详情
import articleComment from '@/_data~/articleComment' // 文章id的评论列表 (待定)

import { errorPrompt } from '@/plugins/error'
import { useBreadsStore } from '@/stores'
import { switches } from '@/config'
const { setBreadCrumbs } = useBreadsStore()
const enableCommentFlag = switches.enableArticleComment

const route = useRoute()
const category = route.params.category  // 这里使用的是分类名，而不是 id
const artId = ref(route.params.id)
const { cateInfo } = useCateInfo(category)
const cateArticle = ref([])

const INDEX = 'index'
const commentInfo = ref([])
const articleInfo = ref(null)
const preNextInfo = ref(null)
const breadcrumbs = ref([])

const displayFixedMenu = ref(false)
const displayFixedToc = ref(false)

watch(cateInfo, () => {
  // 解决 ref 的异步问题
  useArticleList(cateInfo.value.id).then(v => { // 获取分类下的文章列表（异步）
    cateArticle.value = v
    document.title = cateInfo.value.title
    setPrevNext(artId.value)
  }).catch(() => {
    errorPrompt('Fail to get article list')
  })
  breadcrumbs.value[0] = route.params.category
})
watch(() => route.params.id, onRouteChange)
watch(breadcrumbs, (newValue) => {
  const breads = [
    { title: newValue[0], path: '/article/category' },
    { title: newValue[1], path: '#' },
  ]
  setBreadCrumbs(breads)
}, { deep: true })

function onRouteChange() {
  artId.value = route.params.id
  switchArticle(artId.value)
}

onMounted(() => switchArticle(artId.value)) // 原地刷新时，使 info 非 null)

function switchArticle(articleId) {
  commentInfo.value = articleComment.data //articleComment.filter(c => c.articleId == articleId)
  if (articleId == INDEX) {
    breadcrumbs.value[1] = 'summary'
    return
  }
  useArticleInfo(articleId).then(v => { // 获取文章详情（异步）
    articleInfo.value = v
    breadcrumbs.value[1] = articleInfo.value.title
    let title = articleInfo.value.title + ' - ' + cateInfo.value.title
    document.title = title

  }).catch(() => {
    errorPrompt('Fail to get article detail')
  })
  setPrevNext(artId.value)
}
function setPrevNext(articleId) {
  for (let i = 0; i < cateArticle.value.length; i++) {
    const a = cateArticle.value[i]
    if (a.type == 1 && a.children.length) {
      let curIdx = a.children.findIndex(v => v.id == articleId)
      if (curIdx != -1) {
        preNextInfo.value = {
          prev: curIdx === 0 ? undefined : a.children[curIdx - 1],
          next: curIdx === a.children.length ? undefined : a.children[curIdx + 1]
        }
        break
      }
    } else {
      if (a.id == articleId) {
        preNextInfo.value = {
          prev: i === 0 ? undefined : cateArticle.value[i - 1].type == 1 ? undefined : cateArticle.value[i - 1],
          next: i === cateArticle.value.length ? undefined : cateArticle.value[i + 1]
        }
        break
      }
    }
  }
}

function onCommentSubmit(text) {
  // 
}

function onCommentDelete(id) {
  // comments.value = comments.value.filter((_, i) => i !== idx)
}

onMounted(() => {
  const observer = new IntersectionObserver(hideBtn, { threshold: 0.0 })
  const target = document.querySelector('#article-comment')
  const target1 = document.querySelector('#site-footer')
  if (target) observer.observe(target)
  if (target1) observer.observe(target1)

  function hideBtn(entries) {
    const tocBtn = document.getElementById('toc-btn')
    if (tocBtn) tocBtn.style.opacity = entries[0].isIntersecting ? '0' : '1'
    const menuBtn = document.getElementById('menu-btn')
    if (menuBtn) menuBtn.style.opacity = entries[0].isIntersecting ? '0' : '1'
  }
})
</script>

<template>
  <div class="view-container">
    <div class="view-sidebar">
      <MenuBar :article-list="cateArticle" />
    </div>
    <div class="view-main">
      <div v-if="artId == 'index'" class="cate-summary">
        <CateDetail :cateInfo></CateDetail>
      </div>
      <div v-else class="article-container">
        <ArticleDetail :articleInfo :preNextInfo :displayFixedToc />
      </div>
      <div id="article-comment">
        <div class="comment-container" v-if="artId != INDEX">
          <!-- <ArticleComment :commentInfo v-if="enableCommentFlag" @onCommentDelete="onCommentDelete"
            @onCommentSubmit="onCommentSubmit" />
          <div v-else class="prompt">Article comment have been disabled</div> -->
        </div>
      </div>
    </div>
    <div id="menu-btn" @click="displayFixedMenu = true">
      <div class="icon icon-menu"></div>
    </div>
    <div id="toc-btn" v-if="artId != INDEX" @click="displayFixedToc = !displayFixedToc">
      <div class="icon icon-toc"></div>
    </div>
    <div class="fixed-menu" :class="{ 'display-menu': displayFixedMenu }">
      <!-- 所以此组件会加载两次 -->
      <MenuBar :article-list="cateArticle" />
    </div>
    <div class="fixed-mask" :class="{ 'display-mask': displayFixedMenu }" @click="displayFixedMenu = false"></div>
  </div>
</template>

<style scoped lang="scss">
.view-container {
  width: 100%;
  display: grid;
  grid-template-areas: "sidebar main";
  grid-template-columns: 20% 80%;
  min-height: 100vh;

  @media screen and (max-width: 882px) {
    grid-template-areas: "main";
    grid-template-columns: 100%;
  }

  @media screen and (min-width: 883px) and (max-width: 992px) {
    grid-template-areas: "sidebar main";
    grid-template-columns: 25% 75%;
  }
}

.view-sidebar {
  position: sticky;
  top: 0;
  margin-right: 2rem;
  background-color: var(--card-left-side-bgc);
  box-shadow: 0px 2px 6px rgba(60, 83, 54, 0.67);
  border: 1px solid var(--border-secondary);

  @media screen and (max-width: 882px) {
    display: none;
  }
}

.cate-summary {

  @media screen and (max-width: 882px) {
    margin-bottom: 40vh;
  }
}

.view-main {
  margin-top: 20px;
}

.prompt {
  font-size: 1rem;
  color: #767676;
  margin-bottom: 2rem;
  text-align: center;
}

.icon {
  mask-repeat: no-repeat;
  mask-position: center;
  vertical-align: middle;
  display: inline-block;
  width: 20px;
  height: 20px;
}

#menu-btn {
  position: fixed;
  bottom: 15px;
  left: -50px;
  transition: all .5s ease-out;

  cursor: pointer;
  --c: #afcdaf;
  background-color: var(--c);
  border: 10px solid var(--c);
  border-radius: 40px;

  &:hover {
    --c: #cbac94;
  }

  & .icon-menu {
    mask-image: url('/static/svg/menu.svg');
    background-color: #467564;
  }

  @media screen and (max-width: 882px) {
    left: 15px;
  }
}

#toc-btn {
  position: fixed;
  bottom: 15px;
  right: -50px;
  transition: all .5s ease-out;

  cursor: pointer;
  --c: #afcdaf;
  background-color: var(--c);
  border: 10px solid var(--c);
  border-radius: 40px;

  &:hover {
    --c: #cbac94;
  }

  & .icon-toc {
    mask-image: url('/static/svg/toc.svg');
    background-color: #397d51;
  }

  @media screen and (max-width: 992px) {
    right: 15px;
  }
}

.view-sidebar,
.fixed-menu {
  // background-image: url('@/assets/media/d.png');
  background-repeat: no-repeat;
  background-size: contain;
  background-position: right bottom;
}

.fixed-menu {
  position: fixed;
  top: 0;
  left: -55%;
  width: 55%;
  min-width: 200px;
  height: 100%;
  z-index: 999;
  visibility: hidden;
  transition: all .1s linear;
  background-color: var(--card-left-side-bgc);
  box-shadow: 0 2px 4px var(--site-home-shadow);
  border-right: 1px solid var(--border-secondary);
}

.display-menu {
  visibility: visible;
  left: 0;
}

.fixed-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 990;
  visibility: hidden;
  opacity: 0;
  transition: all .3s ease-out;
  background-color: rgba(0, 0, 0, .5);
}

.display-mask {
  visibility: visible;
  opacity: 1;

}
</style>
